package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"io"
	"log"
	"time"

	pb "gogrpc0/grpc/route"
)

func runFirst(clinet pb.RouteGuideClient){
	feature, err := clinet.GetFeature(context.Background(), &pb.Point{Latitude: 310235000,Longitude: 121437403})
	if err != nil {
		log.Fatal("get server message error,the err is: ", err)
	}
	fmt.Println(feature)
}

func runSecond(client pb.RouteGuideClient) {
	serverStream, err := client.ListFeatures(context.Background(), &pb.Rectangle{
		Lo: &pb.Point{Latitude: 313374060, Longitude: 121358540},
		Hi: &pb.Point{Latitude: 311034130, Longitude: 121598790},
	})
	if err != nil {
		log.Fatal("err")
	}
	for {
		feature, err := serverStream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(feature)
	}

}

func runThird(client pb.RouteGuideClient){
	points := []*pb.Point{
		{Latitude: 313374060, Longitude: 121358540},
		{Latitude: 311034130, Longitude: 121598790},
		{Latitude: 310235000, Longitude: 121437403},
	}
	stream, err := client.RecordRoute(context.Background() )
	if err != nil {
		log.Fatal(err)
	}
	for _, point := range points {
		err := stream.Send(point)
		if err != nil {
			log.Fatal(err)
		}
		time.Sleep(time.Second)
	}
	summary, err := stream.CloseAndRecv()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(summary)

}

func main() {
	conn, err := grpc.Dial("localhost:5000", grpc.WithInsecure(),grpc.WithBlock())
	if err != nil {
		log.Fatal("client cannot dial grpcserver")
	}
	defer conn.Close()
	client := pb.NewRouteGuideClient(conn)
	runThird(client)
}
